<?php

namespace app\api\model;

use think\Model;
use traits\model\SoftDelete;

class StudentImages extends Model
{
    use SoftDelete;
    protected $autoWriteTimestamp = 'int';
    protected $createTime = 'createtime';
    protected $updateTime = 'updatetime';
    protected $deleteTime = 'deletetime';
    protected $hidden = ['weigh', 'deletetime', 'updatetime'];

    public function getImagesAttr($value)
    {
        return $value ? request()->domain().$value : '';
    }

    public static function getImagesByStudent($student_id)
    {
        $images = self::where('student_id', $student_id)->order(['createtime desc', 'weigh desc'])->select();
        $dates = self::field(" FROM_UNIXTIME(createtime, '%Y-%m') as date")->group('date')->select();
        $data = [];
        $arr = [];
        foreach ($images as $image) {
            $time = date('Y-m',$image['createtime']);
            foreach ($dates as $val) {
                if ($time == $val['date']) {
                    $arr[$time][] = $image['images'];
                }
            }
        }
        foreach ($arr as $key=>$val) {
            $data[] = [
                'date' => $key,
                'images' => $val
            ];
        }
        return $data;
    }

    public static function getImagesByDate($student_id, $date)
    {
        $start_time = strtotime($date);
        $end_time = $start_time + 24 * 3600 - 1;
        $images = self::where('student_id', $student_id)->whereTime('createtime', 'between', [$start_time, $end_time])->order(['createtime desc', 'weigh desc'])->select();
        return $images;
    }

    /**
     * 新增图片
     */
    public function addImages($student_id, $images)
    {
        $images = explode(',', $images);
        foreach ($images as $key=>$val) {
            $data[] = [
                'student_id' => $student_id,
                'images' => $val,
                'status' => 3,
                'createtime' => time(),
                'updatetime' => time()
            ];
        }
        return $this->insertAll($data);
    }
}
